package com.jxs.android.ges;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.jxs.android.ges.data.A_Case_AttrachMent;
import com.jxs.android.ges.data.A_Case_BussinessInfo;
import com.jxs.android.ges.data.A_Case_Cst_RelationInfo;
import com.jxs.android.ges.data.A_Case_ProtoclInfo;
import com.jxs.android.ges.data.VisitRecordInfo;
import com.jxs.android.util.HandlerHolder;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.util.Timer;
import com.jxs.android.weiget.BuCommonTableView;
import com.jxs.android.weiget.BuCommonTableView_AttachMent_Item;
import com.jxs.android.weiget.BuCommonTableView_Business_Item;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.Bu_A_Case_Protocl_PageView;
import com.jxs.android.weiget.Bu_A_Case_Protocl_PageView.Protocl_Loading_Listener;
import com.jxs.android.weiget.Bu_A_Case_Visit_Record_PageView;
import com.jxs.android.weiget.Bu_A_Case_Visit_Record_PageView.Visit_Record_Loading_Listener;
import com.jxs.android.weiget.Bu_Cst_Relation_Item;
import com.jxs.android.weiget.ScrollContainer;
import com.jxs.android.weiget.TopBar;

/**
 * 一户一案详细界面
 * 
 * @author jxs
 * 
 */
@SuppressLint("HandlerLeak")
public class A_Case_HomePages extends AbstractActivity implements OnPageChangeListener, Visit_Record_Loading_Listener, Protocl_Loading_Listener {

	static public enum PageIndex {
		/** 业务现状 */
		BS_STATUS,
		/** 客户关系 */
		CST_RELATION,
		/** 协议信息 */
		PROTOCL_INFO,
		/** 走访记录 */
		VISIT_RECODS,
		/** 附件信息 */
		ATTACHMENT;
	}

	private ViewPager viewPager;
	private Search_Result_HomePageAdapter viewPagerAdapter;

	private RadioGroup radioGroup;

	private String sys_no;
	private String cust_id;
	public static final String TAG_CUST_ID = "cst_id";
	public static final String TAG_SYS_NO = "sys_no";
	public static final String TAG_SUB_TITLE = "sub_title";

	private List<Boolean> loadStates;
	private A_Case_GetBusinessListHolder getBussinessInfoHolder;/**/
	private A_Case_GetRelationBaseInfoHolder getRelationBaseInfoHoler;/**/
	private A_Case_GetProtocol_InfoHolder getProtocolInfoHolder;/**/
	private A_Case_GetRecordsInfoPageHolder getRecordsInfoPageHolder;
	private A_Case_GetAttrBaseInfoHolder getAttrBaseInfoHolder;
	private TopBar topBar;

	private BuCommonTableView bs_status_view;
	private BuCommonTableView contact_list_View;
	private Bu_A_Case_Protocl_PageView protocl_page_view;
	private Bu_A_Case_Visit_Record_PageView visit_records_page_view;
	private BuCommonTableView attachement_list_View;
	private List<ScrollContainer> containers;
	private final int BASE_PAGE_SIZE = 13;
	private int PAGE_SIZE = BASE_PAGE_SIZE;
	private int vs_currentPage = 1;
	private int p_currentPage = 1;
	private int mTabIndex;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.bu_a_case_result_home_page);

		Bundle data = getIntent().getExtras();
		if (data != null) {
			sys_no = data.getString(TAG_SYS_NO);
			cust_id = data.getString(TAG_CUST_ID);
			if (data.getBoolean("hindTitle", false)) {
				topBar.hindAll();
			}
			if (data.containsKey(TAG_SUB_TITLE)) {
				topBar.setSubTitle(data.getString(TAG_SUB_TITLE));
				topBar.setTitleTextViewGravy(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
			}
		}
		PAGE_SIZE = 15;
		initloadState();
		initWaitDialog();
		setupFlowView();
		initSearchPageHolder();
		getBussinessInfoHolder.getBusinessList(GesApplication.getUserInfo().getTicket(), sys_no);
	}

	private void initSearchPageHolder() {
		getBussinessInfoHolder = new A_Case_GetBusinessListHolder(handler, PageIndex.BS_STATUS.ordinal());
		getRelationBaseInfoHoler = new A_Case_GetRelationBaseInfoHolder(handler, PageIndex.CST_RELATION.ordinal());
		getProtocolInfoHolder = new A_Case_GetProtocol_InfoHolder(handler, PageIndex.PROTOCL_INFO.ordinal());
		getRecordsInfoPageHolder = new A_Case_GetRecordsInfoPageHolder(handler, PageIndex.VISIT_RECODS.ordinal());
		getAttrBaseInfoHolder = new A_Case_GetAttrBaseInfoHolder(handler, PageIndex.ATTACHMENT.ordinal());
	}

	private void initloadState() {
		loadStates = new ArrayList<Boolean>();
		for (int index = 0; index < 5; index++) {
			loadStates.add(false);
		}
		containers = new ArrayList<ScrollContainer>();
	}

	private void setLoadState(int pos, boolean isLoad) {
		containers.get(pos).showLoaing(!isLoad);
		loadStates.set(pos, isLoad);
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		super.topBarLogic(topBar);
		this.topBar = topBar;
		topBar.setTitle(R.string.home_home_a_case);
		topBarReturn(topBar);
		topBar.hindSpinnerBtn();
	}

	private void setupFlowView() {
		radioGroup = (RadioGroup) findViewById(R.id.cutomer_tabs);
		radioGroup.setOnCheckedChangeListener(tabChangedListener);

		viewPager = (ViewPager) findViewById(R.id.viewPager_search);
		initViewPager();
	}

	private void initViewPager() {
		viewPager.setOnPageChangeListener(this);
		viewPagerAdapter = new Search_Result_HomePageAdapter();

		LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		// cust tab
		ScrollContainer bussinessStatusContainer = new ScrollContainer(this);
		containers.add(bussinessStatusContainer);
		bs_status_view = new BuCommonTableView(this);
		bussinessStatusContainer.addView(bs_status_view, lp);
		viewPagerAdapter.addItem(bussinessStatusContainer);

		// 客户关系
		ScrollContainer customerContainer = new ScrollContainer(this);
		containers.add(customerContainer);
		contact_list_View = new BuCommonTableView(this);
		customerContainer.addView(contact_list_View, lp);
		viewPagerAdapter.addItem(customerContainer);

		// 协议信息
		ScrollContainer protoclContainer = new ScrollContainer(this);
		containers.add(protoclContainer);
		protoclContainer.addView(getProtoclView());
		viewPagerAdapter.addItem(protoclContainer);

		// 走访记录
		ScrollContainer attrTableViewContainer = new ScrollContainer(this);
		containers.add(attrTableViewContainer);
		attrTableViewContainer.addView(getVisitRecordsView());
		viewPagerAdapter.addItem(attrTableViewContainer);

		// 附件信息
		ScrollContainer attachementTableViewContainer = new ScrollContainer(this);
		containers.add(attachementTableViewContainer);
		attachement_list_View = new BuCommonTableView(this);
		attachementTableViewContainer.addView(attachement_list_View, lp);
		viewPagerAdapter.addItem(attachementTableViewContainer);

		viewPager.setAdapter(viewPagerAdapter);
	}

	private View getProtoclView() {
		protocl_page_view = new Bu_A_Case_Protocl_PageView(this);
		protocl_page_view.setDataListener(this);
		return protocl_page_view;
	}

	private View getVisitRecordsView() {
		visit_records_page_view = new Bu_A_Case_Visit_Record_PageView(this);
		visit_records_page_view.setDataListener(this);
		return visit_records_page_view;
	}

	private OnCheckedChangeListener tabChangedListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			switch (checkedId) {
			case R.id.tab_business_current:
				viewPager.setCurrentItem(PageIndex.BS_STATUS.ordinal());
				break;
			case R.id.tab_relation:
				viewPager.setCurrentItem(PageIndex.CST_RELATION.ordinal());
				break;
			case R.id.tab_protocl_info:
				viewPager.setCurrentItem(PageIndex.PROTOCL_INFO.ordinal());
				break;
			case R.id.tab_visit_recods:
				viewPager.setCurrentItem(PageIndex.VISIT_RECODS.ordinal());
				break;
			case R.id.tab_attachement:
				viewPager.setCurrentItem(PageIndex.ATTACHMENT.ordinal());
				break;
			}
		}
	};

	@Override
	public void onPageScrollStateChanged(int state) {
		if (state == ViewPager.SCROLL_STATE_IDLE) {
			if (!loadStates.get(mTabIndex)) {
				if (mTabIndex == PageIndex.BS_STATUS.ordinal()) {
					getBussinessInfoHolder.getBusinessList(GesApplication.getUserInfo().getTicket(), sys_no);
				} else if (mTabIndex == PageIndex.CST_RELATION.ordinal()) {
					getRelationBaseInfoHoler.getContactList(GesApplication.getUserInfo().getTicket(), sys_no);
				} else if (mTabIndex == PageIndex.PROTOCL_INFO.ordinal()) {/* 协议 */
					// 2.6.5 getAgreementPage【一户一案详单=》协议信息tab】
					loadingProtocol(p_currentPage);
				} else if (mTabIndex == PageIndex.ATTACHMENT.ordinal()) {
					getAttrBaseInfoHolder.getCaseRemarkList(GesApplication.getUserInfo().getTicket(), sys_no);
				} else if (mTabIndex == PageIndex.VISIT_RECODS.ordinal()) {
					loadingVisitRecords(vs_currentPage);
				}
			}
		}
	}

	@Override
	public void vr_loadingData(int currentPage) {
		loadingVisitRecords(currentPage);
	}

	private void loadingVisitRecords(final int currentPage) {
		getRecordsInfoPageHolder.getVisitsRecordXPage(GesApplication.getUserInfo().getTicket(), "", cust_id, "", "", PAGE_SIZE, currentPage);
	}

	@Override
	public void p_loadingData(int currentPage) {
		loadingProtocol(currentPage);
	}

	private void loadingProtocol(final int currentPage) {
		getProtocolInfoHolder.getAgreementPage(GesApplication.getUserInfo().getTicket(), cust_id, PAGE_SIZE, currentPage);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (MemoryUtil.isCurrentActivity(A_Case_HomePages.class)) {
				if (msg.what == HandlerHolder.What.UPDATE_LIST_UI) {
					if (msg.arg1 == PageIndex.BS_STATUS.ordinal()) {
						updateBussinessStatusList(msg);
					} else if (msg.arg1 == PageIndex.CST_RELATION.ordinal()) {
						updateContactList(msg);
					} else if (msg.arg1 == PageIndex.PROTOCL_INFO.ordinal()) {
						updateProtoclInfoList(msg);
					} else if (msg.arg1 == PageIndex.VISIT_RECODS.ordinal()) {
						updateVisitRecordInfoList(msg);
					} else if (msg.arg1 == PageIndex.ATTACHMENT.ordinal()) {
						updateAttacheMentList(msg);
					}
				} else if (msg.what == HandlerHolder.What.ERROR_MSG) {
					errorMsgPop(msg.obj.toString());
				} else if (msg.what == HandlerHolder.What.TO_LOGIN) {
					errorMsgToLogin(msg.obj.toString());
				}
			}
		}
	};

	private void updateContactList(Message msg) {
		setLoadState(PageIndex.CST_RELATION.ordinal(), true);
		@SuppressWarnings("unchecked")
		List<A_Case_Cst_RelationInfo> tems = (List<A_Case_Cst_RelationInfo>) msg.obj;
		Bu_Cst_Relation_Item titItem = new Bu_Cst_Relation_Item(this);
		titItem.setBackgroud(R.drawable.row0);
		titItem.setValue("序号", "关键人\n名称", "职务分类", "联系方式", "生日");
		titItem.setTextColor(getResources().getColor(R.color.white));
		contact_list_View.addTitle(titItem);
		if (null != tems && !tems.isEmpty()) {
			int i = 1;
			for (A_Case_Cst_RelationInfo info : tems) {
				Bu_Cst_Relation_Item item = new Bu_Cst_Relation_Item(this);
				item.setValue(i + "", info.name, info.type_name, info.phone, info.birthday);
				if (i % 2 == 0) {
					item.setBackgroud(R.drawable.table_row0);
				} else {
					item.setBackgroud(R.drawable.table_row1);
				}
				contact_list_View.addContent(item);
				i++;
			}
		}

	}

	private void updateBussinessStatusList(Message msg) {
		setLoadState(PageIndex.BS_STATUS.ordinal(), true);
		@SuppressWarnings("unchecked")
		List<A_Case_BussinessInfo> tems = (List<A_Case_BussinessInfo>) msg.obj;
		BuCommonTableView_Business_Item titItem = new BuCommonTableView_Business_Item(this);
		titItem.setBackgroud(R.drawable.row0);
		titItem.setproduct_type_nameGravityCenter();
		titItem.setValue("序号", "业务类型", "用户数", "存量收入");
		titItem.setTextColor(getResources().getColor(R.color.white));
		bs_status_view.addTitle(titItem);
		if (null != tems && !tems.isEmpty()) {
			int i = 1;
			for (A_Case_BussinessInfo info : tems) {
				BuCommonTableView_Business_Item item = new BuCommonTableView_Business_Item(this);
				item.setValue(i + "", info.product_type_name, info.serv_num, info.stock_income);
				if (i % 2 == 0) {
					item.setBackgroud(R.drawable.table_row0);
				} else {
					item.setBackgroud(R.drawable.table_row1);
				}
				bs_status_view.addContent(item);
				i++;
			}
		}
	}

	private void updateAttacheMentList(Message msg) {
		setLoadState(PageIndex.ATTACHMENT.ordinal(), true);
		@SuppressWarnings("unchecked")
		List<A_Case_AttrachMent> tems = (List<A_Case_AttrachMent>) msg.obj;
		BuCommonTableView_AttachMent_Item titItem = new BuCommonTableView_AttachMent_Item(this);
		titItem.setBackgroud(R.drawable.row0);
		titItem.setValue("序号", "附件说明", "日期", "下载");
		titItem.setremark_contentdGravityCenter();
		titItem.setTextColor(getResources().getColor(R.color.white));
		attachement_list_View.addTitle(titItem);
		if (null != tems && !tems.isEmpty()) {
			int i = 1;
			for (A_Case_AttrachMent info : tems) {
				BuCommonTableView_AttachMent_Item item = new BuCommonTableView_AttachMent_Item(this);
				String comment_date = "";
				try {
					Date da = Timer.getSDFyyyy_MM_dd_HHmmss().parse(info.add_date);
					comment_date = Timer.getSDFyy_MM_dd_N_HHmmss().format(da);
				} catch (Exception e) {
					comment_date = "";
				}

				item.setValue(i + "", info.remark_content, comment_date, info.fileLists);
				if (i % 2 == 0) {
					item.setBackgroud(R.drawable.table_row0);
				} else {
					item.setBackgroud(R.drawable.table_row1);
				}
				attachement_list_View.addContent(item);
				i++;
			}
		} else {
			attachement_list_View.setEmptyVisibility(View.VISIBLE);
		}
	}

	private void updateVisitRecordInfoList(Message msg) {
		setLoadState(PageIndex.VISIT_RECODS.ordinal(), true);
		@SuppressWarnings("unchecked")
		List<VisitRecordInfo> tems = (List<VisitRecordInfo>) msg.obj;
		boolean flag = false;
		visit_records_page_view.setEmptyVisibility(View.GONE);
		visit_records_page_view.getLoadMoreButton().setEnabled(true);
		if (vs_currentPage == 1) {
			if (tems.size() < 1) {
				visit_records_page_view.setEmptyVisibility(View.VISIBLE);
				visit_records_page_view.getLoadMoreButton().setEnabled(false);
			}
		}
		visit_records_page_view.setVisitRecordInfos(tems);
		if ((tems.size() < PAGE_SIZE) || flag) {
			visit_records_page_view.getLoadMoreButton().setText("数据已全部获取完毕");
			visit_records_page_view.getLoadMoreButton().setEnabled(false);
		} else {
			visit_records_page_view.getLoadMoreButton().setText("查看更多...");
			vs_currentPage++;
			visit_records_page_view.setCurrentPage(vs_currentPage);
			visit_records_page_view.getLoadMoreButton().setEnabled(true);
		}
	}

	private void updateProtoclInfoList(Message msg) {
		setLoadState(PageIndex.PROTOCL_INFO.ordinal(), true);
		@SuppressWarnings("unchecked")
		ArrayList<A_Case_ProtoclInfo> tems = (ArrayList<A_Case_ProtoclInfo>) msg.obj;
		protocl_page_view.initTitle("序号", "协议名称", "签约\n日期", "到期\n日期", "预警\n类型");

		boolean flag = false;
		protocl_page_view.setEmptyVisibility(View.GONE);
		protocl_page_view.getLoadMoreButton().setEnabled(true);
		if (p_currentPage == 1) {
			if (tems.size() < 1) {
				protocl_page_view.setEmptyVisibility(View.VISIBLE);
				protocl_page_view.getLoadMoreButton().setEnabled(false);
			}

		}
		protocl_page_view.setA_Case_ProtoclInfos(tems);

		if ((tems.size() < PAGE_SIZE) || flag) {
			protocl_page_view.getLoadMoreButton().setText("数据已全部获取完毕");
			protocl_page_view.getLoadMoreButton().setEnabled(false);
		} else {
			protocl_page_view.getLoadMoreButton().setText("查看更多...");
			p_currentPage++;
			protocl_page_view.setCurrentPage(p_currentPage);
		}

	}

	private BuLoadingDailog waitDialog;

	public void initWaitDialog() {
		if (waitDialog == null) {
			waitDialog = new BuLoadingDailog(this);
			waitDialog.setCancelable(true);
		}
	}

	@Override
	protected void onStop() {

		if (waitDialog != null) {
			waitDialog.dismiss();
		}
		super.onStop();
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int position) {
		mTabIndex = position;
		setRdBtnStateByPos(position);
	}

	private void setRdBtnStateByPos(int pos) {
		if (pos >= 0 && pos < 5) {
			RadioButton rdBtn = (RadioButton) radioGroup.getChildAt(pos);
			rdBtn.setChecked(true);
		}
	}

}
